/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkHttpRequest.h"
#include "MkHttpUri.h"
#include "MkUtil/MkUtil.h"
#include "MkUtil/MkLog.h"

CMkHttpRequest::CMkHttpRequest()
    : m_Method(MkHttpMethodUnknown)
{

}

Uint32 CMkHttpRequest::OnParseHeaderLine(const MkString& HeaderLine)
{
    /*http://mirrors.nju.edu.cn/rfc/beta/errata/rfc2616.html 5.1
     Request-Line  = Method SP Request-URI SP HTTP-Version CRLF
     HTTP-Version like HTTP/1.1
    */
    MkVector<MkString> VecString;
    Uint32 ErrorCode = CMkUtil::StringSplit(HeaderLine, " ", VecString);
    MkCheckErrorLog(ErrorCode, "split string:%s failed\n", HeaderLine.c_str());
    if (VecString.size() < 3) {
        return InvalidParams;
    }
    m_Method = CMkHttpUtil::GetInstance().GetMkHttpMethod(VecString[0]);
    if (MkHttpMethodUnknown == m_Method) {
        return InvalidParams;
    }
    ErrorCode = m_Uri.ParseUri(VecString[1]);
    MkCheckErrorLog(ErrorCode, "parse uri:%s failed\n", VecString[1].c_str());
    MkVector<MkString> vecTmpString;
    ErrorCode = CMkUtil::StringSplit(VecString[2], "/", vecTmpString);
    MkCheckErrorLog(ErrorCode, "get version:%s failed\n", VecString[2].c_str());
    if (vecTmpString.size() < 2) {
        return InvalidParams;
    }
    SetVersion(vecTmpString[1]);
    return NoneError;
}

Uint32 CMkHttpRequest::GetHeaderLine(MkString& HeaderLine)
{
    HeaderLine.clear();
    //add request line
    MkString strUri;
    m_Uri.ToString(strUri);
    HeaderLine += CMkHttpUtil::GetInstance().GetMethod(m_Method) + " " + strUri + " " + "HTTP/" + GetVersion() + MkEndLine;
    return NoneError;
}

Uint32 CMkHttpRequest::SetUri(const MkString& Uri)
{
    m_Uri.Release();
    return m_Uri.ParseUri(Uri);
}

void CMkHttpRequest::SetUri(const CMkHttpUri& Uri)
{
    m_Uri = Uri;
}

void CMkHttpRequest::Release()
{
    m_Method = MkHttpMethodUnknown;
    m_Uri.Release();
    CMkHttpMessage::Release();
}

CMkHttpRequest::~CMkHttpRequest()
{
    m_Method = MkHttpMethodUnknown;
}